/**
 * 轮询任务
 * 退出条件：返回值存在
 *
 * @param {Function} callback 回调函数
 * @param {Number} delay 延迟时间
 * @returns {Function}
 */
const useInterval = (callback, delay = 1000) => {
  const handleInterval = (...arg) => {
    return new Promise((resolve, reject) => {
      const timer = setInterval(async () => {
        const res = await callback(...arg).catch((error) => {
          clearInterval(timer);
          error && reject(error);
        });
        if (res !== undefined && res !== null && res !== "") {
          clearInterval(timer);
          resolve(res);
        }
      }, delay);
    });
  };

  return handleInterval;
};

export default useInterval;
